package cn.tedu.v2_3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 *  练习: 1.Client 添加 IP 功能
 *       2.Server 关闭通讯、代码简洁、写Client
 */
public class Client {
    private Socket socket;
    private String ip;
    public Client() {
       // ip=socket.getInetAddress().getHostAddress();
        try {
            //ip=socket.getInetAddress().getHostAddress();
            socket=new Socket("127.0.0.1",6666);
        } catch (NullPointerException e) {
            System.out.println("友情提示: IP传入错误导致链接失败~");
        } catch (UnknownHostException e) {
            System.out.println("友情提示: IP传入错误");
        } catch (ConnectException e) {
            System.out.println("客户端链接失败: 建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端失败，提示: 检查IP/端口");
        }
    }
    public void start() {
        PrintWriter pw = null;
        //添加IP功能
        ip=socket.getInetAddress().getHostAddress();
        try {
            //代码优化1:
            OutputStream os = null;
            OutputStreamWriter osw = null;
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter
                    (socket.getOutputStream(),
                            "UTF8")), true);
            System.out.println(ip+"请服务器端说话: ");
            Scanner input = new Scanner(System.in);
            String line = null;
            while (true) {
                //代码优化2:
                pw.println(input.nextLine());
                System.out.println("写出成功~~~");
            }
        }catch (NullPointerException e){
            System.out.println("IO流传输对象，有对象为null,请立马核对。"
                    +"建议: 查看try块中对象可能赋值为null");
        } catch (UnsupportedEncodingException e){
            System.out.println("客户端或者服务器端: 编码集存在问题");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端: IO流操作出现错误");
        } finally {
            if (pw!=null)
                  pw.close();
            if (socket!=null&&!socket.isClosed()){
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭出现异常");
                }
            }
        }
    }
    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
}
